﻿#define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <iostream>
#include <WinSock2.h>
#include <Windows.h>
#include<stdlib.h>
#include<cstdint>
#include<string>
#include<vector>
#include <conio.h>
#include "PublicParam.h"
#include<string>
#pragma comment(lib,"ws2_32.lib")
using namespace std;

const wchar_t myCOM[8] = L"COM4"; //电台串口
const char MotorCOM[8] = "COM3"; //电机串口

char RotatingSpeed[11] = "1000010000";
char RadioBuf[11] = "1000010000";

void CommandDataUnpacked(unsigned char Str[])
{
	
		for (int i = 0; i < 10; i++)
		{
			RadioBuf[i] = Str[i];
			printf("%c ", RadioBuf[i]);
		}
		printf("\n");
	
}

//接收电台指令
DWORD WINAPI Gdread(LPVOID lpParamter)
{
	//打开串口
	HANDLE hHandle = CreateFile(myCOM, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
	if (hHandle == INVALID_HANDLE_VALUE)
	{
		wcout << "Error to open motor port " << myCOM << endl;
		return 0;
	}
	printf("transmission ready!\n");
	//设置串口
	DCB mDCB;
	GetCommState(hHandle, &mDCB);
	mDCB.Parity = NOPARITY;
	mDCB.ByteSize = 8;
	mDCB.StopBits = ONE5STOPBITS;
	mDCB.BaudRate = CBR_9600;
	SetCommState(hHandle, &mDCB);
	//设置读写缓冲
	SetupComm(&mDCB, 1024, 1024);
	//清空缓存
	PurgeComm(&mDCB, PURGE_TXCLEAR | PURGE_RXCLEAR);
	DWORD wCount;
	char* point;
	unsigned char Buf[20];
	unsigned char Str[10] = { '1','0','0' ,'0' ,'0' ,'1' ,'0' ,'0' ,'0' ,'0' };
	while (1)
	{
		if (!ReadFile(hHandle, Buf, sizeof(Buf), &wCount, 0))
		{
			printf("error to receive\n");
		}
		else {
			if (wCount != 0)
			{
				point = strchr((char*)Buf, 'x');
				//验证接收数据流
				if ((point > 0) && (sizeof(Buf) - (point - (char*)Buf) >= 12) && (*(point + 11) == 'e'))
				{
					int k = point - (char*)Buf;
					for (int i = 0; i < 10; i++)
					{
						Str[i] = Buf[k + i + 1];
					}
					CommandDataUnpacked(Str);
				}
				else
				{
					Str[0] = '1';
					Str[1] = '0';
					Str[2] = '0';
					Str[3] = '0';
					Str[4] = '0';
					Str[5] = '1';
					Str[6] = '0';
					Str[7] = '0';
					Str[8] = '0';
					Str[9] = '0';
					printf("receive again transmission data\n");
					Sleep(15);
				}
			}
		}
	}
	CloseHandle(hHandle);
	return 1;
}

//转速信息下发至电机
DWORD WINAPI Motor(LPVOID lpParmter)
{
	/*通过COM口发送转速指令到单片机*/
	Serial* SP = new Serial(MotorCOM);
	int datalength = 11;
	char incomingdata[11];
	while (TRUE)
	{
		strcpy(incomingdata, RadioBuf);
		SP->WriteData(incomingdata, datalength);
		Sleep(20);
	}
	return 1;
}

int main()
{
	//开启电台接收线程
	DWORD drThreadGdread, drParamGdread;
	HANDLE hGdread = CreateThread(NULL, 0, Gdread, &drParamGdread, 0, &drThreadGdread);

	//下发转速至电机
	DWORD drThreadMotor, drParamMotor;
	HANDLE hMotor = CreateThread(NULL, 0, Motor, &drParamMotor, 0, &drThreadMotor);

	WaitForSingleObject(hGdread, INFINITE);
	WaitForSingleObject(hMotor, INFINITE);
	CloseHandle(hGdread);
	CloseHandle(hMotor);
	return 1;
}